<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :model="filters" :inline="true">
				<el-form-item>
					<el-input v-model="filters.keywords" placeholder="关键字" ></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="warning" v-on:click="getCourses">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="addHandler" >新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表v-loading="listLoading"-->
		<el-table @row-click="rowClick" :data="courseRescourse" v-loading="listLoading"
				  highlight-current-row  style="width: 100%;">
			<!--多选框-->
			<el-table-column type="selection" width="55">
			</el-table-column>
			<!--索引值,为什么不用id,id不序号-->
			<el-table-column type="index" width="60">
			</el-table-column>
			<!--其他都设置值,只有一个不设置值就自动适应了-->
			<el-table-column prop="courseId" label="课程id">
			</el-table-column>
			<!--<el-table-column prop="courseType.name" label="类型">-->
			<!--</el-table-column>-->
			<el-table-column prop="resources" label="资源">
<!--        <template scope="scope">-->
<!--          <span>{{scope.row.rescourse}}</span>-->
<!--        </template>-->
			</el-table-column>
			<el-table-column prop="type" label="类型" :formatter="statusFormatter">
			</el-table-column>

			<el-table-column label="操作" width="200">
				<template scope="scope">
					<el-button size="small"  @click="edit(scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"  :page-size="10" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增界面-->
		<el-dialog title="新增" :visible.sync="addFormVisible"  :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px"  ref="addForm">

        <el-form-item label="选择课程" >
          <el-select v-model="addForm.courseId" filterable placeholder="请选择">
            <el-option
                v-for="item in names"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="资源类型">
          <el-select v-model="addForm.type" placeholder="请选择">
            <el-option label="图片" value="0">图片</el-option>
            <el-option label="文件" value="1">文件</el-option>
            <el-option label="视频" value="2">视频</el-option>
          </el-select>
        </el-form-item>

				<el-form-item prop="logo" label="课程封面">
					<!--<el-input type="text" v-model="employee.logo" auto-complete="off" placeholder="请输入logo！"></el-input>-->
          <el-upload
              class="upload-demo"
              action="http://xhy-xhy.oss-cn-chengdu.aliyuncs.com"
              :data="uploadData"
              :before-upload="beforeUpload"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" >提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
    import { quillEditor } from "vue-quill-editor"; //调用编辑器
    import "quill/dist/quill.core.css"
	import "quill/dist/quill.snow.css"
	import "quill/dist/quill.bubble.css"

	export default {
        computed: {
			editor() {
                return this.$refs.myQuillEditor.quill
            }
		},
        components: {//使用编辑器
            quillEditor
        },
		data() {
			return {
        value: '',
        uploadData: {  //提交到OSS的参数
          policy: '',
          signature: '',
          key: '',
          ossaccessKeyId: '',
          dir: '',
          host: ''
        },
          row:"",
          priceDisabled:true,
          editorOption: {},//富文本编辑框配置
        addFormVisible:false,
				names:[],
				//images:[xxx.jgp,xxxx,jpg,xxxx.jpg],
				addForm:{
          courseId:'',
          type:''
				},
        courses: [],
        fileList: [],
        listLoading:false,
				//查询对象
				filters:{
					keywords:''
				},
				page:1,//当前页,要传递到后台的
				total:0, //分页总数
        courseRescourse:[], //当前页数据
			}
		},
		methods: {
      // 修改编辑
      edit(row){
        // 弹出框
        this.addFormVisible = true;
        // 数据回显，Object.assign(a,b)
        this.addForm = Object.assign({},row);
        this.addForm.resources = row.resources;
        this.fileList = [{name:"资源",url:row.resources}]
      },
      // 删除
      handleDel(row) {
        // 弹出确认框
        this.$confirm('确认删除？', '提示', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(()=>{ // 选择确认的回调方法
          // 发送请求
          this.$http.delete("/course/courseResource/"+row.id).then(res=>{
            console.log(res)
            // 返回信息
            let {success,message}=res.data;
            if (success){
              this.$message({
                message: message,
                type: 'success'
              });
            } else {
              this.$message.error('网络异常');
            }
            // 重新加载列表
            this.getCourses();
          })
        }).catch(()=>{  // 选择取消回调方法
          this.$message('已取消');
        })
      },
      getUUID() {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
          s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";
        var uuid = s.join("");
        return uuid;
      },
      async beforeUpload(){
        await this.$http.get("/file/file/sign").then(response=>{
          //设置相关的参数
          var resultObj = response.data.resultObj;
          this.uploadData.policy = resultObj.policy;
          this.uploadData.signature = resultObj.signature;
          this.uploadData.ossaccessKeyId = resultObj.accessid;
          //上传的文件名，使用UUID处理一下
          this.uploadData.key = resultObj.dir + '/'+this.getUUID()+'_${filename}';
          this.uploadData.dir = resultObj.dir;
          this.uploadData.host = resultObj.host;
        });
      },
      handleSuccess(res, file) {
        //this.fileList.pop();
        //上传的完整的文件地址  http://itsource-xx.oss-cn-chengdu.aliyuncs.com/itsource/eiojreojfoiefje.jpg
        var urlPath = this.uploadData.host + '/' + this.uploadData.key.replace("${filename}",file.name) ;
        this.addForm.resources = urlPath;
        this.$message({message: '上传成功，图片地址：'+this.addForm.resources, type: 'success' });
      },
      addSubmit(){
        // 弹出框
        this.addFormVisible = true;
                // this.addForm.type = this.addForm.type[this.addForm.type.length - 1];
				/**

                chargeId: 2
                description: "1111"
                gradeId: 1
                intro: "<p>111<img src=""
                price: "1111"
                qq: "111"
                forUser: "1"
				 **/

        var param = {
            id:this.addForm.id,
            courseId:this.addForm.courseId,
            type:this.addForm.type,
            resources:this.addForm.resources,
				}

          this.$http.post("/course/courseResource/save",param).then(res=>{
            var ajaxResult = res.data;
            if(ajaxResult.success){
              this.$message({
                  message: '保存成功!',
                  type: 'success'
              });
              this.addFormVisible = false;
              this.getCourses();
            }else{
              this.$message({
                  message: '上传失败!',
                  type: 'error'
              });
            }
				});
			},
      getCourseName(){
        this.$http.get("/course/course").then(result=>{
          this.names = result.data;
        });
      },
            changeCharge(chargeId){
                console.log(chargeId);
                if(chargeId === 1){
                    this.priceDisabled = true;
                    this.addForm.price = "";
                    this.addForm.priceOld = "";
				}else{
                    this.priceDisabled = false;
				}
			},
      onEditorReady(editor) {
          //当富文本编辑框初始化好执行
      },
      addHandler(){
        this.fileList = [];
        this.addForm ={
          id: '',
          courseId: '',
          resources: '',
          type: ''
        }
				this.addFormVisible = true;
			},
            handleCurrentChange(curentPage){
                this.page = curentPage;
                this.getCourses();
			},
            getCourses(){
                //发送Ajax请求后台获取数据  axios
				//添加分页条件及高级查询条件
				let para = {
				    "page":this.page,
					"keyword":this.filters.keywords
				};
				this.listLoading = true; //显示加载圈
				//分页查询
        this.$http.post("/course/courseResource/list",para) //$.Post(.....)
            .then(result=>{
              console.log(result);
                this.total = result.data.total;
                this.courseRescourse = result.data.rows;
                this.listLoading = false;  //关闭加载圈
            });
			},
      rowClick(row){
				this.row = row;
				console.log(this.row);
			},
      //性别显示转换
      statusFormatter: function (row, column) {
          return row.type == 0 ? '图片' : row.type == 1 ? '文件' : '视频';
      },
		},
		mounted() {
		    this.getCourses();
		    this.getCourseName();
		}
	}

</script>

<style scoped>

</style>